package com.wangzeqi.changliaoba.messege;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.EMCallBack;
import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.ImageMessageBody;
import com.easemob.chat.TextMessageBody;
import com.easemob.chat.VoiceMessageBody;
import com.wangzeqi.changliaba.dao.ChatInformation;
import com.wangzeqi.changliaba.dao.ChatInformationDao;
import com.wangzeqi.changliaoba.R;
import com.wangzeqi.changliaoba.base.BaseActivity;
import com.wangzeqi.changliaoba.singleton.AllSingleTon;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import de.greenrobot.dao.query.DeleteQuery;
import de.greenrobot.dao.query.QueryBuilder;

/**
 * Created by dllo on 16/3/2.
 */
public class ChatActivity extends BaseActivity implements View.OnClickListener, EMEventListener, MyClick {
    private ImageView imageViewBack;
    private TextView textViewToName;
    private ImageView imageViewDeleteAll;

    private GridView gridView;
    private GridViewOfMessegeAdapter adapterOfGridview;

    private EditText editTextMessegeContent;
    private Button buttonChatActivity;
    private RecyclerView messegesList;
    private RelativeLayout relativeLayoutSendYuyin;
    private RelativeLayout relativeLayoutTxt;
    private ImageView imageViewAdd;
    private ImageView imageViewBiaoqing;
    private ImageView imageViewYuyin;
    private ImageView imageViewJianpan;
    private Button btnSendYuyin;
    private ArrayList<ChatInformations> chatInformationsData = new ArrayList<>();
    private RecyclerViewOfMessegeAdapter adapter;
    private String username;
    private ArrayList<ChatInformation> data = new ArrayList<>();
    private QueryBuilder qb;
    private File send_sound_file;
    private MediaRecorder mediaRecorder;


    private TextView textViewCopy;
    private TextView textViewZhuanfa;
    private TextView textViewShoucang;
    private TextView textViewDelete;

    public static Handler handler = new Handler();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sendmessege);
        Intent intent = getIntent();
        username = intent.getStringExtra("username");
        relativeLayoutSendYuyin = (RelativeLayout) findViewById(R.id.messege_yuyin_rl);
        relativeLayoutTxt = (RelativeLayout) findViewById(R.id.messege_txt_rl);
        imageViewBack = (ImageView) findViewById(R.id.messege_back_iv);
        textViewToName = (TextView) findViewById(R.id.messege_toname_tv);
        textViewToName.setText(username);
        imageViewDeleteAll = (ImageView) findViewById(R.id.messege_delete_iv);
        messegesList = (RecyclerView) findViewById(R.id.messege_rv);
        editTextMessegeContent = (EditText) findViewById(R.id.test_messege_et);
        buttonChatActivity = (Button) findViewById(R.id.test_messege_send_btn);
        imageViewAdd = (ImageView) findViewById(R.id.messege_add_iv);
        imageViewBiaoqing = (ImageView) findViewById(R.id.messege_biaoqing);
        imageViewYuyin = (ImageView) findViewById(R.id.messege_yuyin);
        imageViewJianpan = (ImageView) findViewById(R.id.messege_jianpan);
        btnSendYuyin = (Button) findViewById(R.id.messege_sendyuyin);


        gridView = (GridView) findViewById(R.id.messege_gridview);
        adapterOfGridview = new GridViewOfMessegeAdapter(this);
        gridView.setAdapter(adapterOfGridview);

        buttonChatActivity.setOnClickListener(this);
        imageViewAdd.setOnClickListener(this);
        imageViewBack.setOnClickListener(this);
        imageViewDeleteAll.setOnClickListener(this);
        imageViewBiaoqing.setOnClickListener(this);
        imageViewYuyin.setOnClickListener(this);
        imageViewJianpan.setOnClickListener(this);
        btnSendYuyin.setOnClickListener(this);
        editTextMessegeContent.addTextChangedListener(
                new MessegeChangeListener(buttonChatActivity, imageViewAdd, editTextMessegeContent));

        qb = AllSingleTon.getOurInstance().getDaoSession().getChatInformationDao().queryBuilder();
        qb.where(ChatInformationDao.Properties.User_name.eq(username));
        if (qb.list().size() > 0) {
            data = (ArrayList<ChatInformation>) qb.list();
            for (int i = 0; i < data.size(); i++) {
                chatInformationsData.add(0, new ChatInformations(username, data.get(i).getType(), data.get(i).getContent()));
            }
        }

        adapter = new RecyclerViewOfMessegeAdapter(this, chatInformationsData);
        adapter.setMyClick(this);
        ForwardActivity.setMyClick(this);
        SelectSendPicture.setMyClick(this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        linearLayoutManager.setReverseLayout(true);
        messegesList.setLayoutManager(linearLayoutManager);
        messegesList.setAdapter(adapter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.test_messege_send_btn:
                if (editTextMessegeContent.getText().toString().trim().length() > 0) {
                    //获取到与聊天人的会话对象。参数username为聊天人的userid或者groupid，后文中的username皆是如此
//                Log.d("ChatActivity", username);
                    EMConversation conversation = EMChatManager.getInstance().getConversation(username);
//创建一条文本消息
                    final EMMessage message = EMMessage.createSendMessage(EMMessage.Type.TXT);
//如果是群聊，设置chattype,默认是单聊
//                message.setChatType(ChatType.GroupChat);
//                message.setChatType(EMMessage.ChatType.GroupChat);
//设置消息body
                    TextMessageBody txtBody = new TextMessageBody(editTextMessegeContent.getText().toString());
                    message.addBody(txtBody);
//设置接收人

                    message.setReceipt(username);

//把消息加入到此会话对象中
                    conversation.addMessage(message);
/**
 * 消息送达BroadcastReceiver
 */
//发送消息
                    EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
                        @Override
                        public void onSuccess() {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    chatInformationsData.add(0, new ChatInformations(username, 1, editTextMessegeContent.getText().toString()));
                                    AllSingleTon.getOurInstance().getDaoSession().getChatInformationDao().insert(new ChatInformation(username, 1, editTextMessegeContent.getText().toString()));

                                    adapter.notifyDataSetChanged();
                                    imageViewAdd.setVisibility(View.VISIBLE);
                                    buttonChatActivity.setVisibility(View.INVISIBLE);

                                    String[] data = new String[]{username, editTextMessegeContent.getText().toString(), getTime()};
                                    Message message1 = new Message();
                                    message1.what = 100;
                                    message1.obj = data;
                                    handler.sendMessage(message1);
                                    editTextMessegeContent.setText("");
                                }
                            });
                            Log.d("ChatActivity", "success");
                        }

                        @Override
                        public void onError(int i, String s) {
                            Log.d("ChatActivity", i + "---error----" + s);
                        }

                        @Override
                        public void onProgress(int i, String s) {
                            Log.d("ChatActivity", i + "---onProgress----" + s);
                        }
                    });
                } else {
                    Toast.makeText(this, "消息内容为空", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.messege_back_iv:
                finish();
                break;
            //删除全部聊天记录
            case R.id.messege_delete_iv:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("删除全部记录").setMessage("确定要删除吗?").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        QueryBuilder<ChatInformation> queryBuilder = AllSingleTon.getOurInstance().getDaoSession().getChatInformationDao().queryBuilder();
                        DeleteQuery<ChatInformation> deleteQuery = queryBuilder.where(ChatInformationDao.Properties.User_name.eq(username)).buildDelete();
                        deleteQuery.executeDeleteWithoutDetachingEntities();
                        chatInformationsData.removeAll(chatInformationsData);
                        adapter.notifyDataSetChanged();
                    }
                }).setNegativeButton("取消", null).show();
                break;
            //发送消息模式
            case R.id.messege_add_iv:
                gridView.setVisibility(View.VISIBLE);
                Toast.makeText(this, "敬请期待", Toast.LENGTH_SHORT).show();
                break;
            case R.id.messege_biaoqing:
                gridView.setVisibility(View.GONE);
                Toast.makeText(this, "敬请期待", Toast.LENGTH_SHORT).show();
                break;
            case R.id.messege_yuyin:
                relativeLayoutSendYuyin.setVisibility(View.VISIBLE);
                relativeLayoutTxt.setVisibility(View.GONE);
                break;
            case R.id.messege_jianpan:
                relativeLayoutTxt.setVisibility(View.VISIBLE);
                relativeLayoutSendYuyin.setVisibility(View.GONE);
                break;
            //发送语音消息
            case R.id.messege_sendyuyin:
                btnSendYuyin.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        switch (event.getAction()) {
                            case MotionEvent.ACTION_DOWN:
                                Log.d("ChatActivity", "开始录音");
                                startRecord();
                                break;
                            case MotionEvent.ACTION_UP:
                                Log.d("ChatActivity", "停止录音");
                                stopRecord();
                                EMConversation conversation = EMChatManager.getInstance().getConversation(username);
                                final EMMessage message = EMMessage.createSendMessage(EMMessage.Type.VOICE);
//如果是群聊，设置chattype,默认是单聊
                                VoiceMessageBody body = new VoiceMessageBody(send_sound_file, (int) send_sound_file.length());
                                message.addBody(body);
                                message.setReceipt(username);
                                conversation.addMessage(message);
                                EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
                                    @Override
                                    public void onSuccess() {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                chatInformationsData.add(0, new ChatInformations(username, 5, send_sound_file.getAbsolutePath()));
                                                adapter.notifyDataSetChanged();
                                                Log.d("ChatActivity", "success");
                                                Log.d("ChatActivity", message.getBody().toString());
                                            }
                                        });
                                    }

                                    @Override
                                    public void onError(int i, String s) {
                                        Log.d("ChatActivity", "ERROR");
                                    }

                                    @Override
                                    public void onProgress(int i, String s) {
                                        Log.d("ChatActivity", "PROGRESS");
                                    }
                                });
                                break;
                        }
                        return false;
                    }
                });
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        EMChatManager.getInstance().registerEventListener(this, new EMNotifierEvent.Event[]{EMNotifierEvent.Event.EventNewMessage,
                EMNotifierEvent.Event.EventOfflineMessage, EMNotifierEvent.Event.EventDeliveryAck,
                EMNotifierEvent.Event.EventReadAck});
        QueryBuilder qb = AllSingleTon.getOurInstance().getDaoSession().getChatInformationDao().queryBuilder();
        qb.where(ChatInformationDao.Properties.User_name.eq(username));
        Log.d("ChatActivity", "resume");
    }


    @Override
    protected void onPause() {
        super.onPause();
        adapter.notifyDataSetChanged();
        Log.d("ChatActivity", "pause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        adapter.notifyDataSetChanged();
        EMChatManager.getInstance().unregisterEventListener(this);
        Log.d("ChatActivity", "stop");
    }


    //RecyclerListViewItem 的点击事件接口实现方法
    @Override
    public void onClick(final int position, final String s) {
        final Dialog dialog = new Dialog(this);
        View view = LayoutInflater.from(ChatActivity.this).inflate(R.layout.chat_dialog, null);
        dialog.setContentView(view);
        dialog.setTitle("请选择操作");
        dialog.show();

        textViewCopy = (TextView) view.findViewById(R.id.dialog_fuzhi);
        textViewZhuanfa = (TextView) view.findViewById(R.id.dialog_zhuanfa);
        textViewShoucang = (TextView) view.findViewById(R.id.dialog_shoucang);
        textViewDelete = (TextView) view.findViewById(R.id.dialog_shanchu);

        textViewCopy.setOnClickListener(this);
        //消息转发
        textViewZhuanfa.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(ChatActivity.this, textViewZhuanfa.getText().toString(), Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(ChatActivity.this, ForwardActivity.class);
                intent.putExtra("zhuanfa_messege", s);
                dialog.cancel();
                startActivity(intent);
            }
        });
        textViewShoucang.setOnClickListener(this);
        //删除单个聊天记录
        textViewDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                QueryBuilder<ChatInformation> queryBuilder = AllSingleTon.getOurInstance().getDaoSession().getChatInformationDao().queryBuilder();
                DeleteQuery<ChatInformation> deleteQuery = queryBuilder.where(ChatInformationDao.Properties.Content.eq(s)).buildDelete();
                deleteQuery.executeDeleteWithoutDetachingEntities();
                chatInformationsData.remove(position);
                adapter.notifyDataSetChanged();
                dialog.cancel();
            }
        });
    }

    //转发后改变页面
    @Override
    public void ForwardMessegeChanged() {
        QueryBuilder qb1 = AllSingleTon.getOurInstance().getDaoSession().getChatInformationDao().queryBuilder();
        qb1.where(ChatInformationDao.Properties.User_name.eq(username));
        if (qb1.list().size() > 0) {
            data = (ArrayList<ChatInformation>) qb.list();

            chatInformationsData.add(0, new ChatInformations(username, data.get(data.size() - 1).getType(), data.get(data.size() - 1).getContent()));

        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void deleteFriend(String friendName) {

    }


    //发送图片
    @Override
    public void sendPictures(final ArrayList<String> datas) {
        for (int i = 0; i < datas.size(); i++) {
            EMConversation conversation = EMChatManager.getInstance().getConversation(username);
            EMMessage message = EMMessage.createSendMessage(EMMessage.Type.IMAGE);


//如果是群聊，设置chattype,默认是单聊
//            message.setChatType(EMMessage.ChatType.GroupChat);

            ImageMessageBody body = new ImageMessageBody(new File(datas.get(i)));
            Log.d("ChatActivity", datas.get(i));
// 默认超过100k的图片会压缩后发给对方，可以设置成发送原图
//            body.setSendOriginalImage(true);
            message.addBody(body);
            message.setReceipt(username);
            conversation.addMessage(message);
            final int finalI = i;
            EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
                @Override
                public void onSuccess() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            chatInformationsData.add(0, new ChatInformations(username, 3, datas.get(finalI)));
                            AllSingleTon.getOurInstance().getDaoSession().getChatInformationDao().insert(new ChatInformation(username, 3, datas.get(finalI)));
                            adapter.notifyDataSetChanged();
                            Log.d("ChatActivity", "success");
                        }
                    });
                }

                @Override
                public void onError(int i, String s) {
                    Log.d("ChatActivity", "error");
                }

                @Override
                public void onProgress(int i, String s) {
                    Log.d("ChatActivity", "progress");
                }
            });
        }
    }

    //获取发送时间
    public String getTime() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        return format.format(date);
    }

    //开始录音方法
    private void startRecord() {
        String path = null;
        try {
            send_sound_file = new File(Environment.getExternalStorageDirectory().getCanonicalFile() + "/talk/send");
            if (!send_sound_file.exists()) {
                send_sound_file.mkdirs();
            }
            path = Environment.getExternalStorageDirectory().getCanonicalFile() + "/talk/send/" + getTime() + ".amr";
        } catch (IOException e) {
            e.printStackTrace();
        }
        send_sound_file = new File(path);
        mediaRecorder = new MediaRecorder();
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        // 设置录制的声音的输出格式（必须在设置声音编码格式之前设置）
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        // 设置声音编码的格式
        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        mediaRecorder.setOutputFile(send_sound_file.getAbsolutePath());
        try {
            mediaRecorder.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 开始录音
        mediaRecorder.start();
    }

    //停止录音方法
    public void stopRecord() {
        if (send_sound_file != null && send_sound_file.exists()) {
//            ses_id = ses_id + 1;
            // 停止录音
            mediaRecorder.stop();
            // 释放资源
            mediaRecorder.release();
            mediaRecorder = null;
        }
    }
    //加号 功能点击事件


    // 接受消息监听
    @Override
    public void onEvent(EMNotifierEvent emNotifierEvent) {
        final EMMessage message = (EMMessage) emNotifierEvent.getData();
        Log.d("TAGGG", "onEvent() called with: " + "emNotifierEvent = [" + message.getFrom() + "]" + Thread.currentThread().getName());
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d("ChatActivity", message.getType() + "");
                        Log.d("ChatActivity", message.getBody().toString());

                        switch (message.getType() + "") {
                            case "TXT":
                                String s = message.getBody().toString().substring(5);
                                String s1 = s.substring(0, (s.length() - 1));
                                chatInformationsData.add(0, new ChatInformations(username, 2, s1));
                                AllSingleTon.getOurInstance().getDaoSession().getChatInformationDao().insert(new ChatInformation(username, 2, s1));
                                adapter.notifyDataSetChanged();
                                break;
                            case "IMAGE":

                                String imageUrl = message.getBody().toString().substring(message.getBody().toString().lastIndexOf("http"), message.getBody().toString().length());
                                Log.d("ChatActivity", message.getBody().toString());
                                Log.d("ChatActivity", imageUrl);
                                chatInformationsData.add(0, new ChatInformations(username, 4, imageUrl));
                                AllSingleTon.getOurInstance().getDaoSession().getChatInformationDao().insert(new ChatInformation(username, 4, imageUrl));
                                adapter.notifyDataSetChanged();
                                break;
                            case "VOICE":

                                Log.d("ChatActivity", message.getBody().toString());
                                String voiceUrl = message.getBody().toString().substring(message.getBody().toString().lastIndexOf("localurl:"), message.getBody().toString().lastIndexOf(",remoteurl"));
                                chatInformationsData.add(0, new ChatInformations(username, 6, voiceUrl));
                                AllSingleTon.getOurInstance().getDaoSession().getChatInformationDao().insert(new ChatInformation(username, 6, voiceUrl));
                                adapter.notifyDataSetChanged();
                                break;

                        }

                    }
                });

            }
        });

    }
}
